package com.kfm.bootdemo.controller;

import com.kfm.bootdemo.model.KfmUser;
import com.kfm.bootdemo.model.Result;
import com.kfm.bootdemo.model.Student;
import com.kfm.bootdemo.service.StudentService;
import com.kfm.bootdemo.service.UserService;
import com.kfm.bootdemo.util.Constant;
import com.kfm.bootdemo.util.ValidUtils;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    private UserService service = new UserService();

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    // url --> 方法一一对应   Map(url, 类名+方法名)
    // thyemleaf 识别到字符串 会去 resources 目录中的 templates 中找字符串名称的html
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    // request 解析请求参数
    // 可以将请求参数中的key和方法中的形参一一对应
    @PostMapping("/login")
    public String login(String username, String password, String captcha, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        // 处理登录逻辑
        boolean ver = CaptchaUtil.ver(captcha, request);
        if (!ver) {
            CaptchaUtil.clear(request);
            session.setAttribute(Constant.MESSAGE_KEY, "验证码错误！");
            return "login";
        }
        CaptchaUtil.clear(request);
        KfmUser login = service.login(username, password);
        if (login == null) {
            session.setAttribute(Constant.MESSAGE_KEY, "登录失败！");
            return "login";
        }
        session.setAttribute(Constant.LOGIN_USER_KEY, login);
        session.setAttribute(Constant.MESSAGE_KEY, "登录成功！");
        // 成功

//        response.sendRedirect("/index");
        // 重定向到 /index 请求
        return "redirect:/index";
    }

    @RequestMapping("/test")
    public String test() {
        return "test";
    }

    @RequestMapping("/all")
    public String all(HttpServletRequest request, HttpServletResponse response) {
//        request.getRequestDispatcher("/test.html").forward(request, response);
        return "forward:/test";
    }

    // /avatar/xx.jpg
    @RequestMapping("/avatar")
    public void avatar(String name, HttpServletRequest request, HttpServletResponse response) {
        // 头像的 file 对象
        File file = new File(Constant.AVATAR_PATH + File.separator + name);
        // 告诉浏览器响应的是二进制流
        response.setContentType("application/octet-stream");
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            in.transferTo(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/register")
    public String register(String username, String password, String confirm_password,
                           String captcha, String email, HttpServletRequest request,
                           HttpSession session, RedirectAttributes redirectAttributes) {
        boolean ver = CaptchaUtil.ver(captcha, request);
        if (!ver) {
            CaptchaUtil.clear(request);
//            session.setAttribute(Constant.MESSAGE_KEY, "验证码错误！");
            redirectAttributes.addFlashAttribute(Constant.MESSAGE_KEY, "验证码错误！");
            return "redirect:/login";
        }
        CaptchaUtil.clear(request);

        if (password == null || !password.equals(confirm_password)) {
//            session.setAttribute("msg", "密码不一致");
            redirectAttributes.addFlashAttribute(Constant.MESSAGE_KEY, "密码不一致！");
            return "redirect:/login";
        }

        // username长度必须在5位以上 不能有中文不能以数字开头
        if (!ValidUtils.validUsername(username)) {
//            session.setAttribute("msg", "用户名不规范，字母开头，允许5-16字节，允许字母数字下划线");
            redirectAttributes.addFlashAttribute(Constant.MESSAGE_KEY, "用户名不规范，字母开头，允许5-16字节，允许字母数字下划线！");
            return "redirect:/login";
        }

        // 校验email
        if (!ValidUtils.validEmail(email)) {
//            session.setAttribute("msg", "邮箱地址不正确");
            redirectAttributes.addFlashAttribute(Constant.MESSAGE_KEY, "邮箱地址不正确");
            return "redirect:/login";
        }
        // 密码强度校验
        if (!ValidUtils.validPassword(password)) {
//            session.setAttribute("msg", "以字母开头，长度在6~18之间，只能包含字母、数字和下划线");
            redirectAttributes.addFlashAttribute(Constant.MESSAGE_KEY, "密码不正确，以字母开头，长度在6~18之间，只能包含字母、数字和下划线");
            return "redirect:/login";
        }

        int rows = service.register(username, password, email);
        if (rows > 0) {
//            session.setAttribute("msg", "注册成功，请登录");
            redirectAttributes.addFlashAttribute(Constant.MESSAGE_KEY, "注册成功，请登录");
            return "redirect:/login";
        }

        redirectAttributes.addFlashAttribute(Constant.MESSAGE_KEY, "注册失败，请重新注册");
        return "redirect:/login";
    }

    @RequestMapping("/info")
    @ResponseBody
    public Student[] info() {
        Student student = new Student();
        student.setId(1);
        student.setName("张一健");
        student.setBirth(new Date());
        Student s2 = new Student(2,"李国伟",new Date(), "男");
        Student s3 = new Student(3,"婉君",new Date(), "女");
        Student s4 = new Student(4,"徐婧",new Date(), "女");
        Student[] students = {student, s2, s3, s4};
        return students;
    }

    private StudentService studentService = new StudentService();

    @RequestMapping("/list")
    // 将返回的内容直接响应给客户端
    @ResponseBody
    public Result list() {
        List<Student> all = studentService.findAll();
        if (all != null) { // 查询成功
            return Result.success("查询成功", all);
        }
        return Result.failure("查询失败");
    }

    // ModelAndView 可以返回页面并携带数据
    // setViewName() 设置返回的页面
    // addObject(key, value) 设置携带的数据,可以设置多个  在视图层 ${key}
    // addAllObjects(map) 设置多个数据
    @RequestMapping("/mv")
    public ModelAndView mv() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("mv");
        Student s2 = new Student(2,"李国伟",new Date(), "男");
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "查询成功");
        map.put("stu", s2);
        modelAndView.addAllObjects(map);
//        modelAndView.addObject("msg", "hello modelAndView");
//        modelAndView.addObject("stu", s2);
        return modelAndView;
    }
}
